<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ weatherDescription }}，{{ weatherTemp }}
                </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.project') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.project"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.toDo') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.todo"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" border-style="dashed" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.access') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.access"
                  :duration="2600"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <el-skeleton :loading="loading" animated>
                <Echart :options="lineOptions" :height="320" />
        </el-skeleton>
      </el-card>

      <el-card shadow="never" class="mt-8px">
        <el-skeleton :loading="loading" animated>
          <el-row :gutter="20" justify="space-between">
            <el-col :xl="10" :lg="10" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="pieOptionsData" :height="320" />
                </el-skeleton>
              </el-card>
            </el-col>
            <el-col :xl="14" :lg="14" :md="24" :sm="24" :xs="24">
              <el-card shadow="hover" class="mb-8px">
                <el-skeleton :loading="loading" animated>
                  <Echart :options="barOptionsData" :height="320" />
                </el-skeleton>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.shortcutOperation') }}</span>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col v-for="item in shortcut" :key="`team-${item.name}`" :span="8" class="mb-8px">
              <div class="flex items-center">
                <Icon :icon="item.icon" class="mr-8px" />
                <el-link type="default" :underline="false" @click="jupmTo(item.url)">
                  {{ item.name }}
                </el-link>
              </div>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
      <el-card shadow="never" class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.notice') }}</span>
            <el-link type="primary" :underline="false" @click="navigate">{{ t('action.more') }}</el-link>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
    <div class="notice-container">
      <div v-for="(item, index) in notice" :key="`dynamics-${index}`" class="notice-item" @click="handleAudit(item.id,item.processInstanceId)">
        <div class="flex items-center">
          <el-avatar :src="avatar" :size="35" class="mr-16px">
            <img src="@/assets/imgs/avatar.gif" alt="" />
          </el-avatar>
          <div >
            <div class="text-14px">
              <Highlight :keys="item.keys.map((v) => t(v))">
                {{ item.processInstance.name }} : {{ item.name }}
              </Highlight>
            </div>
            <div class="mt-16px text-12px text-gray-400">
              {{ formatTime(item.createTime, 'yyyy-MM-dd') }}
            </div>
          </div>
        </div>
        <el-divider />
      </div>
    </div>
  </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'

import { useUserStore } from '@/store/modules/user'
import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions,lineOptions } from './echarts-data'
import axios from '@/config/axios'
import { WeatherFetcherVO, IndexApi } from '@/api/wms/index'
import * as TaskApi from '@/api/bpm/task'

defineOptions({ name: 'Home' })
const { push } = useRouter() // 路由

const { t } = useI18n()
const userStore = useUserStore()
const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})



// 初始化天气描述和温度
let weatherDescription = ref(''); // 初始化一个空字符串作为默认值
let weatherTemp = ref(''); // 初始化一个空字符串作为默认值
let weatherDataLoaded = ref(false); // 标记天气数据是否已加载
onMounted(async () => {
  try {
    const weatherFetcher = await IndexApi.getWeatherFetcher();
    
    if (weatherFetcher) {
      weatherDescription.value = weatherFetcher.description || '无天气描述';
      weatherTemp.value = weatherFetcher.temp ? `${Math.round(weatherFetcher.temp)}℃` : '未知温度';
      weatherDataLoaded.value = true; // 更新数据加载状态
    }
  } catch (error) {
    console.error("获取天气数据失败:", error);
    alert('无法获取天气数据，请检查网络连接。');
  } finally {
    loading.value = false; // 确保加载状态最终被设置为 false
  }
});

const jupmTo = async (url: any) => {
  console.log(url)
  push(url)
}

const navigate = async () => {
  push('bpm/task/todo')
}

const getCount = async () => {
  const orderAll = await IndexApi.getOrderAllByUser()
  const orderSuccess = await IndexApi.getOrderByUser()
  const taskData = await TaskApi.getTaskTodoPage(queryParams)
  const data = {
    project: orderAll,
    access: taskData.total,
    todo: orderAll-orderSuccess
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    {
      name: 'ruoyi-vue-pro',
      icon: 'akar-icons:github-fill',
      message: 'https://github.com/YunaiV/ruoyi-vue-pro',
      personal: 'Spring Boot 单体架构',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vue3',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vue3',
      personal: 'Vue3 + element-plus',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vben',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vben',
      personal: 'Vue3 + vben(antd)',
      time: new Date()
    },
    {
      name: 'yudao-cloud',
      icon: 'akar-icons:github',
      message: 'https://github.com/YunaiV/yudao-cloud',
      personal: 'Spring Cloud 微服务架构',
      time: new Date()
    },
    {
      name: 'yudao-ui-mall-uniapp',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-uniapp',
      personal: 'Vue3 + uniapp',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vue2',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vue2',
      personal: 'Vue2 + element-ui',
      time: new Date()
    }
  ]
  projects = Object.assign(projects, data)
}
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  createTime: []
})
// 获取通知公告
let notice = reactive<Notice[]>([])
const list = ref([]) // 列表的数据

const getNotice = async () => {
    const data = ref([])
    const taskData = await TaskApi.getTaskTodoPage(queryParams)
    list.value = taskData.list
    list.value = list.value.map(item => ({
    ...item,
      keys: Array.isArray(item.keys) ? item.keys : []
    }));

  notice = Object.assign(notice, list.value)
}

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    {
      name: '销售订单',
      icon: 'ep:shopping-cart-full',
      url: 'sale/sale-order'
    },
    {
      name: '销售出库',
      icon: 'fa:sign-out',
      url: 'sale/rdrecord32'
    },
    {
      name: '采购订单',
      icon: 'ep:folder-opened',
      url: 'store/pomain'
    },
    {
      name: '采购入库',
      icon: 'ep:top',
      url: 'store/rdrecord01'
    },
    {
      name: '生产任务单',
      icon: 'ep:bicycle',
      url: 'product/production-order'
    },
    {
      name: '生产入库',
      icon: 'ep:download',
      url: 'product/rdrecord10'
    }
  ]
  shortcut = Object.assign(shortcut, data)
}

const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

// 折线图
const getlineOptions = async () => {
  const monthData = await IndexApi.getMonth();
  const orderAll = await IndexApi.getLineOrderAll();
  const orderSuccess = await IndexApi.getLineOrderSuccess();
  set(
    lineOptionsData,
    'xAxis.data',
    monthData
  )
  lineOptionsData!.series![0].data = orderAll.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
  lineOptionsData!.series![1].data = orderSuccess.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}

const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 存货
const getUserAccessSource = async () => {
  const data =await IndexApi.getStock();
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 单据量
const getWeeklyUserActivity = async () => {
  const data = await IndexApi.getOrder();
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.orderQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    getNotice(),
    getShortcut(),
    getUserAccessSource(),
    getWeeklyUserActivity(),
    getlineOptions()
  ])
  loading.value = false
}

getAllApi()

/** 处理审批按钮 */
const handleAudit = (id:any,processInstanceId: any) => {
  console.log(id+processInstanceId)
  push({
    name: 'BpmProcessInstanceDetail',
    query: {
      id: processInstanceId,
      taskId: id
    }
  })
}


</script>

<style scoped>
.notice-container {
  height: 540px; /* 设置最大高度 */
  overflow-y: auto;   /* 超出部分显示滚动条 */
}

.notice-item {
  padding: 8px 0; /* 可选：为每个通知项添加一些内边距 */
}

.flex {
  display: flex;
  align-items: center;
}

.mr-16px {
  margin-right: 16px;
}

.text-14px {
  font-size: 14px;
}

.text-12px {
  font-size: 12px;
}

.text-gray-400 {
  color: #a0a0a0;
}

.mt-16px {
  margin-top: 16px;
}
</style>
